# build options
BUILD_PATH = build

TOOL_CHAIN ?= arm-none-eabi-
IMAGE=kernel.elf

MKDIR=mkdir -p

CC = $(TOOL_CHAIN)gcc
AR = $(TOOL_CHAIN)ar
LD = $(TOOL_CHAIN)ld
OBJCOPY = $(TOOL_CHAIN)objcopy
OBJDUMP = $(TOOL_CHAIN)objdump
GDB = $(TOOL_CHAIN)gdb

TARGET = -mcpu=cortex-m33

CFLAGS = -Os -ffunction-sections -fdata-sections -Wall -Wa,-adhlns="$@.lst" \
	   -fmessage-length=0 $(TARGET) -mthumb -mfpu=fpv4-sp-d16 -mfloat-abi=softfp \
	   -g3 -gdwarf-2 -gstrict-dwarf

				
INC_DIRS = inc . freertos freertos/portable freertos/include

CFLAGS += $(patsubst %, -I ./%,$(INC_DIRS))

LDFLAGS = -T env/link.ld

SRC=$(wildcard src/*.c) $(wildcard env/*.c) $(wildcard drv/*.c) \
	$(wildcard freertos/*.c) $(wildcard freertos/portable/*.c)

OBJS=$(addprefix $(BUILD_PATH)/,$(addsuffix .o,$(basename $(SRC))))


.PHONY: clean flash_loader

all: $(OBJS)
	$(CC) $(CFLAGS) $(LDFLAGS) -o $(IMAGE) $(OBJS) 
	$(OBJDUMP) -h -D -t kernel.elf > kernel.map


$(BUILD_PATH)/%.o: %.c
	@$(MKDIR) -p $(dir $@)
	$(CC) $(CFLAGS) -c -o $@ $<

dumpvmstate:
	qemu-system-arm -machine musca-b1 -cpu cortex-m33 \
	                    -m 1024 \
			    -nographic -serial mon:stdio \
	                    -kernel $(IMAGE) \
			    -dump-vmstate vmstate.json 

qemu:
	@qemu-system-arm -M ? | grep musca-b1 >/dev/null || exit
	qemu-system-arm -machine musca-b1 -cpu cortex-m33 \
	                    -m 4096 \
			    -nographic -serial mon:stdio \
	                    -kernel $(IMAGE) 
			   
gdbserver:
	qemu-system-arm -machine musca-b1 -cpu cortex-m33 \
	                    -m 4096 \
			    -nographic -serial mon:stdio \
	                    -kernel $(IMAGE) \
			    -S -s 
gdb: $(IMAGE)
	$(GDB) $^ -ex "target remote:1234"


gdbqemu:
	gdb --args qemu-system-arm -machine musca-b1 -cpu cortex-m33  -m 4096  -nographic -serial mon:stdio -kernel kernel.elf

clean:
	rm -rf build*
	rm -f *.elf *.asm *.srec *.map *.bin *.sim
	rm -f tags
